package com.android.aconportable;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;


public class UDPSocket {
	
	private InetAddress ipAddress;
	private int peerPort;
	private int localPort;
	DatagramSocket socket;
	DatagramPacket packet;
	byte[] buff;
	private static final int buffsize = 1024;//4096;
	
	
	public UDPSocket(InetAddress ipAddress, int peerPort, int localPort){
		this.ipAddress = ipAddress;
		this.peerPort = peerPort;
		this.localPort = localPort;
		
		buff = new byte[buffsize];
		packet = new DatagramPacket(buff, buff.length);
	}
		
	//use boolean later
	
	public void connect(){
		try {
			socket = new DatagramSocket(localPort);
			socket.connect(ipAddress, peerPort);
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
	
	public void send(byte[] buff, int size) throws IOException{
		packet.setData(buff,0,size);
		socket.send(packet);
	}
	
	public DatagramPacket receive(int size){
		try {
			socket.receive(packet);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return packet;
	}
	
	public boolean isConnect(){
		return socket.isConnected();
	}
	
	public void close(){
		socket.close();
	}

}
